package com.qiku.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qiku.reggie.common.R;
import com.qiku.reggie.pojo.Category;
import com.qiku.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;


    /**
     * 新增分类
     */
    @PostMapping
    public R<String> add(@RequestBody Category category){
        categoryService.save(category);
        return R.success("新增成功");
    }


    /**
     * 分页查询
     * required 是否带默认值   默认为true      defaultValue 设置值
     */
    @GetMapping("/page")
    public R<Page<Category>> page(@RequestParam(name = "page" , required = false , defaultValue = "1") Integer page ,
                                  @RequestParam(name = "pageSize" , required = false , defaultValue = "10") Integer pageSize){

        // 构造分页对象
        Page<Category> pageInfo = new Page<>(page , pageSize);

        // 构造条件对象
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        // 排序 降序   如果排序一样按时间
        queryWrapper.orderByAsc("sort").orderByDesc("update_time");

        // 分页查询
        categoryService.page(pageInfo , queryWrapper);
        return R.success(pageInfo);
    }


    /**
     * 删除分类 但是当此分类关联菜品或套餐时 不允许删除
     */
    @DeleteMapping
    public R<String> deleteById(Long id){
        categoryService.remove(id);
        return R.success("删除分类成功");
    }


    /**
     * 修改分类信息
     */
    @PutMapping
    public R<String> update(@RequestBody Category category){
        // 调用 updateById 方法  传入category对象中一定要有id属性
        categoryService.updateById(category);
        return R.success("修改成功");
    }


    /**
     * 根据type查询分类列表
     */
    @GetMapping("/list")
    public R<List<Category>> list(Integer type){
        // 构造条件
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(type != null ,"type" , type);
        // 查询数据
        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }


}
